﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using TuKu.Load;
using System.Net;
using System.Text.RegularExpressions;
using TuKu.Common;
using System.IO;
using System.Diagnostics;
using System.Threading;

namespace TuKu
{
    public partial class ppsForm : Form
    {
        private static readonly string ImagePattern = @"((http(s)?://)?)+(((/?)+[\w-.]+(/))*)+[\w-./]+\.+(jpg|jpeg|png|ico|bmp|gif)";
        private List<string> urlList = new List<string>();
        Model.urltable model = new global::TuKu.Model.urltable();
        BLL.urltable bll = new global::TuKu.BLL.urltable();
        WebClient wClient = new WebClient();
        private int CurrentID = 1;
        private int pagecount = 0;
        public ppsForm()
        {
            InitializeComponent();
        }

        private void ppsForm_Load(object sender, EventArgs e)
        {
            init();
        }
        private void init()
        {            //http://tu.pps.tv/pics/(*)/index.html
            string maxid = new BLL.urltable().getMaxid();
            if (!String.IsNullOrEmpty(maxid))
            {
                txts.Text = maxid.Replace("http://tu.pps.tv/pics/", "").Replace("/index.html", "");
                txte.Text = (int.Parse(txts.Text) + 1000).ToString();
            }
            else
            {
                txts.Text = "160";
            }
            getFalseCount();
        }
        private void txtTran_Click(object sender, EventArgs e)
        {
            DateTime stime = DateTime.Now;
            //string path = @"d:\pps\pics\";
            int end = int.Parse(txte.Text);
            int begin = int.Parse(txts.Text);
            wClient.Credentials = CredentialCache.DefaultCredentials;


            LoadingHandler.Show(this, LoadingStyle.Progress, args =>
               {
                   args.MaxValue = end - begin;


                   for (int i = begin; i < end; i++)
                   {

                       try
                       {
                           args.Execute(ex =>
                           {
                                doRegexUrl("http://tu.pps.tv/pics/" + i.ToString() + "/index.html",true);
                      
                           });
                       }
                       catch
                       {
                           continue;
                       }

                       args.Value++;
                       args.Change();
                       System.Threading.Thread.Sleep(50);

                   }
               });
            TimeSpan span = DateTime.Now - stime;
            string msg = "处理" + (end - begin).ToString() + "条记录，用时" + span.ToString() + "秒";
            msg.showBox();
            init();
        }
        /// <summary>
        /// 处理页面中的正则
        /// </summary>
        /// <param name="url">地址</param>
        /// <param name="save">是否将地址存入数据库</param>
        /// <returns></returns>
        private string doRegexUrl(string url,bool save)
        {
            string pageData = string.Empty;
            Model.urltable model =  new global::TuKu.Model.urltable();
            model.url = url;
            pageData = Encoding.Default.GetString(wClient.DownloadData(model.url));
            Match matchTitle = Regex.Match(pageData, @"<h3>(.+)</h3>", RegexOptions.IgnoreCase);//获取标题
            Match matchPage = Regex.Match(pageData, @"<div(.+)picPage(.+)</div>", RegexOptions.IgnoreCase);//获取分页代码
            Match matchCategory = Regex.Match(pageData, @"<div(.+)您现在在的位置(.+)</div>", RegexOptions.IgnoreCase);//获取分类标题
            Match matchPicpage = Regex.Match(pageData, @"(?<=<div\s*class=""picShow""\s*id=""ps"">)[\s\S]*?(?=</div>)", RegexOptions.IgnoreCase);//获取图片信息
            Regex re = new Regex(@"http://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?", RegexOptions.IgnoreCase);//定义链接
            MatchCollection mc = re.Matches(matchPage.Value);//获取链接

            if (matchTitle.Success && matchPage.Success)
            {
                model.title = matchTitle.Value.ToString().ToLower().Replace("<h3>", "").Replace("</h3>", "");
                //((mc.Count-1).ToString()+matchPage.Value).showBox();
                //if (!Directory.Exists(path + i.ToString()))
                //Directory.CreateDirectory(path + i.ToString());
                //if (!File.Exists(path + i.ToString() + "\\index.html"))
                //FileManager.WriteFile(path + i.ToString() + "\\index.html", pageData, false);
                //for (int page = 0; page < mc.Count - 2; page++)
                //{
                //if (!File.Exists(path + i.ToString() + "\\" + (page + 2).ToString() + ".html"))
                //FileManager.WriteFile(path + i.ToString() + "\\" + (page + 2).ToString() + ".html", Encoding.Default.GetString(wClient.DownloadData(mc[page].ToString())), false);
                //}
                model.finish = false;
                model.pagenumber = mc.Count - 1;
                model.categoryName = matchCategory.Value;
                model.picPage = Regex.Match(matchPicpage.Value, ImagePattern, RegexOptions.IgnoreCase).Value;
                model.categoryid = 0;
                if (save)
                {
                    if (!bll.Exist(model.url))
                    {
                        bll.Add(model);
                    }
                }
            }
            return model.picPage;
        }

        private void txts_TextChanged(object sender, EventArgs e)
        {
           
                int value = int.Parse(txts.Text);
                txte.Text = (value + 10).ToString();
            


        }

        private void btn_get_Click(object sender, EventArgs e)
        {
            List<Model.urltable> list = new BLL.urltable().GetModelList(" pagenumber>0 ");
            lstUrl.Items.Clear();
            foreach (Model.urltable model in list)
            {
                lstUrl.Items.Add(model.id.ToString() + "." + model.url);
            }

            this.ParentForm.WindowState = FormWindowState.Maximized;
        }

        private void lstUrl_SelectedIndexChanged(object sender, EventArgs e)
        {
            CurrentID = 1;
            download();
        }
        /// <summary>
        /// 下载页面并显示
        /// </summary>
        /// <param name="url"></param>
        private void download()
        {
            int id = int.Parse(lstUrl.SelectedItem.ToString().Split('.')[0].ToString());
            string url = lstUrl.SelectedItem.ToString().Substring(lstUrl.SelectedItem.ToString().IndexOf('.') + 1).ToLower();
            model = new BLL.urltable().GetModel(id);
            //处理分页地址
            if (model.pagenumber > 2)
            {
                for (int i = 2; i <= model.pagenumber; i++)
                {
                    urlList.Add(url.Replace("index", i.ToString()));
                }
                pagecount = urlList.Count;
                imgPageDown.Visible = true;
                //imgPageUp.Visible = true;
            }


            groupDisplay.Text = model.title + "_1 (1/" + model.pagenumber.ToString() + ")";

            if (mySave(model.picPage))
            {
                model.finish = true;
                new BLL.urltable().Update(model);
                this.webBrowser1.DocumentText = "<img src='" + model.picPage + "'/><br/>存放于<a href='" + model.picPage.Replace("http://", "d:/").Replace("/", "\\") + "'>" + model.picPage.Replace("http://", "d:/").Replace("/", "\\") + "</a>";
            }
            else
            {
                this.webBrowser1.DocumentText = "<h1>下载出错</h1>";
            }
        }

        /// <summary>
        /// 双击打开IE显示
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void lstUrl_DoubleClick(object sender, EventArgs e)
        {
            this.ParentForm.WindowState = FormWindowState.Minimized;
            using (Process p = new Process())
            {
                if (File.Exists("C:\\Program Files\\Mozilla Firefox\\firefox.exe"))
                {
                    p.StartInfo.FileName = "C:\\Program Files\\Mozilla Firefox\\firefox.exe";
                }
                else
                {
                    p.StartInfo.FileName = "IEXPLORE.EXE";
                }
                p.StartInfo.Arguments = lstUrl.SelectedItem.ToString().Substring(lstUrl.SelectedItem.ToString().IndexOf('.') + 1);
                p.Start();
            }

        }
        /// <summary>
        /// 上翻页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void imgPageUp_Click(object sender, EventArgs e)
        {
            imgPageDown.Visible = true;
            if (CurrentID > 2)
            {
                CurrentID--;
            }
            else
            {
                CurrentID = 2;
                imgPageUp.Visible = false;
            }
            string url = model.url.Replace("index", CurrentID.ToString());
            showinfo(url);
        }
       /// <summary>
       /// 下翻页
       /// </summary>
       /// <param name="sender"></param>
       /// <param name="e"></param>
        private void imgPageDown_Click(object sender, EventArgs e)
        {
            imgPageUp.Visible = true;
            if (CurrentID < model.pagenumber)
            {
                CurrentID++;
            }
            else
            {
                CurrentID = model.pagenumber;
                imgPageDown.Visible = false;
            }
            string url = model.url.Replace("index", CurrentID.ToString());
            showinfo(url);
        }
        /// <summary>
        /// 保存图片并显示
        /// </summary>
        /// <param name="url"></param>
        private void showinfo(string url)
        {
           
            string img = doRegexUrl(url, false);
            
            groupDisplay.Text = model.title + "_" + CurrentID.ToString() + " (" + CurrentID.ToString() + "/" + model.pagenumber.ToString() + ")";
            if (mySave(img))
            {
                this.webBrowser1.DocumentText = "<img src='" + img + "'/><br/>存放于<a href='" + img.Replace("http://", "d:/").Replace("/", "\\") + "'>" + img.Replace("http://", "d:/").Replace("/", "\\") + "</a>";
            }
            else
            {
                this.webBrowser1.DocumentText = "<h1>下载出错</h1>";
            }
        }

        /// <summary>
        /// 将图片存入本地
        /// </summary>
        /// <param name="url">图片URL,.jpg</param>
        /// <returns></returns>
        private bool mySave(string url)
        {
            bool result = false;
            string p = url;
            if (p.StartsWith("http://"))
            {
                p = p.Replace("http://", "");
                string[] paths = p.Split('/');
                StringBuilder path = new StringBuilder();
                path.Append("d:\\");
                if (paths.Length > 0)
                {
                    for (int i = 0; i < paths.Length - 1; i++)
                    {
                        path.Append(paths[i]);
                        if (!Directory.Exists(path.ToString()))
                            Directory.CreateDirectory(path.ToString());
                        path.Append("\\");
                    }
                }
                if (!File.Exists(path + paths[paths.Length - 1]))
                {
                    LoadingHandler.Show(this, args =>
                    {
                        HttpWebRequest hwr = (HttpWebRequest)HttpWebRequest.Create(url);
                        using (Stream stream = hwr.GetResponse().GetResponseStream())
                        {
                            Image img = Image.FromStream(stream);
                            img.Save(path + paths[paths.Length - 1]);
                            stream.Close();
                        }
                    });
                }
                result = true;
            }
            return result;
        }

        private void btnGetFalse_Click(object sender, EventArgs e)
        {
            textBox1.Text = "";
            string strsql = " select top "+txtFalseCount.Text+" id,url from urltable where pagenumber = -1 and finish = 0 order by id desc ";
            DataTable dt =Maticsoft.DBUtility.DbHelperOleDb.Query(strsql).Tables[0];
            string pageData = string.Empty;
            TuKu.Model.urltable model = new TuKu.Model.urltable();
            StringBuilder sb = new StringBuilder();
            int i = 0;
            foreach (DataRow dr in dt.Rows)
            {
                pageData = Encoding.Default.GetString(wClient.DownloadData(dr["url"].ToString()));

                Match matchPicpage = Regex.Match(pageData, @"(?<=<div\s*class=""picShow""\s*id=""ps"">)[\s\S]*?(?=</div>)", RegexOptions.IgnoreCase);//获取图片信息
                Match matchPage = Regex.Match(pageData, @"<div(.+)picPage(.+)</div>", RegexOptions.IgnoreCase);//获取分页代码
                Match matchCategory = Regex.Match(pageData, @"<div(.+)您现在在的位置(.+)</div>", RegexOptions.IgnoreCase);//获取分类标题
                Regex re = new Regex(@"http://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?", RegexOptions.IgnoreCase);//定义链接
                MatchCollection mc = re.Matches(matchPage.Value);//获取链接

                if (matchPage.Success && matchPicpage.Success)
                {
                    model.pagenumber = mc.Count - 1;
                    model.categoryName = matchCategory.Value;
                    model.picPage = Regex.Match(matchPicpage.Value, ImagePattern, RegexOptions.IgnoreCase).Value;
                    if (model.pagenumber > 0)
                    {
                        strsql = "update urltable set pagenumber=" + model.pagenumber + ",finish=1,categoryName='" + model.categoryName + "',picPage='" + model.picPage + "' where id=" + dr["id"].ToString();
                        Maticsoft.DBUtility.DbHelperOleDb.ExecuteSql(strsql);
                        i++;
                    }
                }
                sb.Append(dr["id"].ToString() + ",");
            }
            strsql = "update urltable set finish=1 where id in ( "+sb.ToString()+"0 )";
            Maticsoft.DBUtility.DbHelperOleDb.ExecuteSql(strsql);
            textBox1.Text = sb.ToString();
            getFalseCount();
            MessageBox.Show("分析" + dt.Rows.Count.ToString() + "条数据,更新"+i.ToString()+"条记录");
        }
        private void getFalseCount()
        {
            string strsql = " select count(*) from urltable where pagenumber = -1 and finish = 0 ";
            lblShowFalse.Text = "未处理记录数:" + Maticsoft.DBUtility.DbHelperOleDb.GetSingle(strsql);
        }



    }
}
